package Network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
   private Socket socket = null;
    public TCPEchoClient(String serverIp,int serverPort) throws IOException {
        //这样就可以根服务器建立连接
        socket = new Socket(serverIp,serverPort);
    }

    public void start () {
        System.out.println("客户端启动！！！");

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {

            Scanner scanner = new Scanner(System.in);

            Scanner scannerNetWork = new Scanner(inputStream);
            while(true) {
                //1. 从控制台读取请求
                System.out.println("请输入要发送的请求：");
                String request = scanner.next();
                request += "\n";
                //2. 把请求发送给服务器
               outputStream.write(request.getBytes());

                //3. 从服务器读取响应
                if(!scannerNetWork.hasNext()) {
                    break;
                }
               String response = scannerNetWork.next();
                //4. 将响应打印在控制台
                System.out.println(response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9090);
        client.start();
    }

}
